<template>
    <div class="task-im">
        <el-dialog :visible.sync="open" @close="handleClose" :close-on-click-modal="false" :title="title" width="700px">
            <div class="chat-container">
                <div class="chat-list" ref="chatList">
                    <ul>
                        <li v-for="(item, index) in msgList">
                            <div class="chat-item">
                                <span class="sender" :class="{ 'is-my': userInfo.userId == item.userId }">{{ userInfo.userId == item.userId ? "我" : item.userName }}:</span>
                                <div class="content">
                                    <template v-if="item.msgType == 'text'">
                                        {{ item.msgContent }}
                                    </template>
                                    <template v-else>
                                        <el-button type="success" :icon="!item.audioPlaying ? 'el-icon-video-play' : ''" @click="playAudioMsg(index)" size="mini">{{ item.audioPlaying ? "播放中..." : "点击播放" }}</el-button>
                                    </template>
                                </div>
                                <span class="time">{{ item.msgTime }}</span>
                            </div>
                        </li>
                    </ul>
                </div>
                <div class="chat-inputer">
                    <el-row class="chat-type-choose">
                        <el-button class="audio" type="text" icon="el-icon-microphone" @click="changeChatType" v-if="chatType == 'text'">切换语音消息</el-button>
                        <el-button class="audio" type="text" icon="el-icon-chat-line-square" @click="changeChatType" v-else>切换文字消息</el-button>
                    </el-row>
                    <el-row class="text-inputer" v-if="chatType == 'text'">
                        <!-- 捕获输入框中回车事件 -->
                        <el-form @submit.native.prevent>
                            <el-input :style="{ width: '100%' }" v-model="content" placeholder="请输入内容"></el-input>
                            <el-button class="send" type="primary" @click="sendMsg">发送消息</el-button>
                        </el-form>
                    </el-row>
                    <el-row class="text-inputer" v-if="chatType == 'audio'">
                        <!-- 捕获输入框中回车事件 -->
                        <el-form @submit.native.prevent>
                            <el-button class="send" type="primary" icon="el-icon-mic" @click="startRecord" v-if="audioStatus == 0">开始录音</el-button>
                            <el-button class="send" type="primary" icon="el-icon-video-pause" @click="stopRecord" v-if="audioStatus == 1">停止录音</el-button>
                            <el-button class="send" type="primary" icon="el-icon-video-play" @click="playAudio" v-if="audioStatus == 2">回放录音</el-button>
                            <el-button class="send" type="primary" icon="el-icon-s-promotion" @click="handleAudioMsgSend" v-if="audioStatus == 2">发送语音消息</el-button>
                            <el-button class="send" type="primary" icon="el-icon-delete" @click="deleteRecord" v-if="audioStatus == 2">取消</el-button>
                        </el-form>
                    </el-row>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import dialogMixin from "@/mixins/dialogMixin";
import { getGroupMsg } from "@/api/chat/im.js";
import moment from "moment";
import TaskMsg from "@/plugins/chat/msgType/TaskMsg";
import * as Auth from "@/utils/auth";
import audioMixin from "./mixins/audioMixin";
export default {
    name: "TaskIM",
    mixins: [dialogMixin, audioMixin],
    data() {
        return {
            title: "",
            content: "",
            taskId: 0,
            type: "",
            handleId: 0,
            userInfo: null,
            msgList: [],
            lastTimestamp: 0,
            timer: null,
            needScroll: true,
            chatType: "text",
            audioStatus: 0,
        };
    },
    methods: {
        openChat(userName, taskId, type, handleId) {
            this.title = userName != "" ? `与 ${userName} 的任务沟通` : "任务沟通";
            this.taskId = taskId;
            this.type = type;
            this.handleId = handleId;
            this.userInfo = Auth.getUserInfo();
            this.show();
            this.$nextTick(() => {
                this.addScrollListener();
            });
            this.getMsgs();
        },
        getMsgs() {
            getGroupMsg(this.type, this.handleId, this.taskId, this.lastTimestamp).then(res => {
                res.data.forEach(d => {
                    d.audioPlaying = false;
                    this.msgList.push(d);
                });
                if (res.data.length > 0) {
                    this.lastTimestamp = moment(res.data[res.data.length - 1].msgTime, "YYYY-MM-DD HH:mm:ss").unix() + 1;
                }
                if (this.needScroll) {
                    this.scrollToBottom();
                }
                this.$chat.setTaskListener(this.taskId, msgBody => {
                    console.log("收到消息", msgBody);
                    let msg = JSON.parse(msgBody.body);
                    let newMsg = {
                        messageId: "",
                        msgType: msg.msgType,
                        msgContent: msg.content,
                        msgTime: moment().format("YYYY-MM-DD HH:mm:ss"),
                        userId: msg.userId,
                        userName: msg.userName,
                        audioPlaying: false,
                    };
                    this.msgList.push(newMsg);
                    this.$nextTick(() => {
                        this.scrollToBottom();
                    });
                });
            });
        },
        sendMsg() {
            let msg = new TaskMsg();
            msg.setType(this.type).setGroupId(this.handleId).setTaskId(this.taskId).setUserId(this.userInfo.userId).setUserName(this.userInfo.userName).setMsgType(this.chatType).setContent(this.content);
            this.$chat.sendTaskMsg(msg, "task");
            this.content = "";
            this.scrollToBottom();
        },
        sendAudioMsg(audioUrl) {
            let msg = new TaskMsg();
            msg.setType(this.type).setGroupId(this.handleId).setTaskId(this.taskId).setUserId(this.userInfo.userId).setUserName(this.userInfo.userName).setMsgType(this.chatType).setContent(audioUrl);
            this.$chat.sendTaskMsg(msg, "task");
            this.content = "";
            this.scrollToBottom();
        },
        addScrollListener() {
            // 监听this.$refs.chatList的滚动
            this.$refs.chatList.addEventListener("scroll", () => {
                // 滚动到底部时，设置needScroll为true，用于在获取消息时自动滚动到底部
                console.log(this.$refs.chatList.scrollTop + this.$refs.chatList.clientHeight, this.$refs.chatList.scrollHeight);
                this.needScroll = this.$refs.chatList.scrollTop + this.$refs.chatList.clientHeight >= this.$refs.chatList.scrollHeight;
            });
        },
        scrollToBottom() {
            this.$nextTick(() => {
                // 自动滚动到底部
                this.$refs.chatList.scrollTop = this.$refs.chatList.scrollHeight;
            });
        },
        handleClose() {
            this.msgList = [];
            this.lastTimestamp = 0;
            this.$chat.clearChatListener();
            this.close();
        },
        handleEnter(event) {
            event.preventDefault();
        },
        changeChatType() {
            this.chatType = this.chatType == "text" ? "audio" : "text";
        },
        playAudioMsg(msgIndex) {
            const msg = this.msgList[msgIndex];
            // 播放音频url
            // 创建 Audio 实例
            const audio = new Audio();
            audio.src = msg.msgContent;

            // 播放音频
            audio.play().catch(error => {
                console.error("播放失败:", error);
            });
            this.msgList[msgIndex].audioPlaying = true;

            // 监听事件
            audio.addEventListener("ended", () => {
                console.log("音频播放结束");
                this.msgList[msgIndex].audioPlaying = false;
            });
        },
    },
};
</script>
<style lang="scss" scoped>
.chat-container {
    color: white;
    border-radius: 10px;
    // padding: 15px;

    .chat-list {
        overflow-y: scroll;
        height: 300px;
        padding: 5px 15px;
        border-radius: 5px;
        background-color: var(--el-color-primary-light-9);

        // 设置滚动条宽度
        &::-webkit-scrollbar {
            width: 8px !important;
            height: 8px !important;
            background: rgba(10, 122, 227, 0.01);
        }

        //滚动条的哈滑块
        &::-webkit-scrollbar-thumb {
            background: #2e6190;
            border-radius: 3px;
        }

        li {
            margin-bottom: 5px;

            // 通过css缩放实现一个0.5像素的底部边框
            &::after {
                content: "";
                display: block;
                width: 100%;
                height: 0;
                border-bottom: 1px solid rgba(255, 255, 255, 1);
                transform: scaleY(0.2);
                transform-origin: 0 0;
                margin-top: 5px;
            }

            &:last-child {
                &::after {
                    border-bottom: 0;
                }
            }
        }

        .chat-item {
            font-size: 12px;
            line-height: 25px;
            display: flex;

            .sender {
                &.is-my {
                    color: var(--el-color-primary);
                }
            }

            .content {
                flex: 1;
                margin: 0 10px;
            }

            .time {
                width: 70px;
                text-align: center;
                line-height: 15px;
                margin-top: 3px;
            }
        }
    }

    .chat-inputer {
        margin-top: 5px;
        .chat-type-choose {
        }
        .text-inputer {
            display: flex;
            margin-top: 5px;
            .el-form {
                width: 100%;
                display: flex;

                .el-button.send {
                    margin-left: 10px;
                }
            }
        }
    }
}

ul,
li {
    padding: 0;
    margin: 0;
}

li {
    list-style: none;
}
</style>
